/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.WebIDE.ejb.sessions;

import java.io.File;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.WebIDE.ejb.entities.*;
import org.WebIDE.ejb.sessions.exceptions.*;

/**
 *
 * @author huy
 */
@Stateless
public class FilesFacade implements FilesFacadeLocal, FilesFacadeRemote {
    @Resource
    private UserTransaction utx = null;
    @PersistenceContext(unitName = "WebIDE-ejbPU")
    private EntityManager _em;
/*
    public void create(Files files) {
        em.persist(files);
    }

    public void edit(Files files) {
        em.merge(files);
    }
*/
    public EntityManager getEntityManager() {
        return _em;
    }
    public void remove(Files files) {
        _em.remove(_em.merge(files));
    }

    public Files find(Object id) {
        return _em.find(Files.class, id);
    }

    public List<Files> findAll() {
        return _em.createQuery("select object(o) from Files as o").getResultList();
    }
    public void create(Files files) throws PreexistingEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Projects projectId = files.getProjectId();
            if (projectId != null) {
                projectId = em.getReference(projectId.getClass(), projectId.getId());
                files.setProjectId(projectId);
            }
            em.persist(files);
            if (projectId != null) {
                projectId.getFilesCollection().add(files);
                projectId = em.merge(projectId);
            }
            //utx.commit();
            File f = new File(projectId.getName()+"/"+files.getName());
            f.createNewFile();
            
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findFiles(files.getId()) != null) {
                throw new PreexistingEntityException("Files " + files + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void edit(Files files) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Files persistentFiles = em.find(Files.class, files.getId());
            Projects projectIdOld = persistentFiles.getProjectId();
            Projects projectIdNew = files.getProjectId();
            if (projectIdNew != null) {
                projectIdNew = em.getReference(projectIdNew.getClass(), projectIdNew.getId());
                files.setProjectId(projectIdNew);
            }
            files = em.merge(files);
            if (projectIdOld != null && !projectIdOld.equals(projectIdNew)) {
                projectIdOld.getFilesCollection().remove(files);
                projectIdOld = em.merge(projectIdOld);
            }
            if (projectIdNew != null && !projectIdNew.equals(projectIdOld)) {
                projectIdNew.getFilesCollection().add(files);
                projectIdNew = em.merge(projectIdNew);
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = files.getId();
                if (findFiles(id) == null) {
                    throw new NonexistentEntityException("The files with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Files files;
            try {
                files = em.getReference(Files.class, id);
                files.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The files with id " + id + " no longer exists.", enfe);
            }
            Projects projectId = files.getProjectId();
            if (projectId != null) {
                projectId.getFilesCollection().remove(files);
                projectId = em.merge(projectId);
            }
            em.remove(files);
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public List<Files> findFilesEntities() {
        return findFilesEntities(true, -1, -1);
    }

    public List<Files> findFilesEntities(int maxResults, int firstResult) {
        return findFilesEntities(false, maxResults, firstResult);
    }

    private List<Files> findFilesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Files as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            //em.close();
        }
    }

    public Files findFiles(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Files.class, id);
        } finally {
            //em.close();
        }
    }

    public int getFilesCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Files as o").getSingleResult()).intValue();
        } finally {
            //em.close();
        }
    }
}
